package com.txsj.scan.db;


import android.database.sqlite.SQLiteDatabase;

import com.greendao.DaoMaster;
import com.greendao.DaoSession;
import com.txsj.scan.MyApplication;


/**
 * Created by wangchuangjun 2018/10/29
 */

public class GreenDaoUtils {
    private static DaoMaster.DevOpenHelper mHelper;
    private static SQLiteDatabase db;
    private static DaoMaster mDaoMaster;
    private static DaoSession mDaoSession;

    private static GreenDaoUtils greenDaoUtils;

    private GreenDaoUtils() {
    }

    public static GreenDaoUtils getSingleTon() {
        if (greenDaoUtils == null) {
            greenDaoUtils = new GreenDaoUtils();
        }
        return greenDaoUtils;
    }

    /**
     * 判断是否有存在数据库，如果没有则创建
     */
    private static void initGreenDao() {
        mHelper = new DaoMaster.DevOpenHelper(MyApplication.getInstance(), "scan-db", null);
        db = mHelper.getWritableDatabase();
        mDaoMaster = new DaoMaster(db);
        mDaoSession = mDaoMaster.newSession();
    }

    /**
     * 完成对数据库的添加、删除、修改、查询操作，
     */
    public static DaoSession getmDaoSession() {
        if (mDaoMaster == null) {
            initGreenDao();
        }
        return mDaoSession;
    }

    public void deleteAll(){
        getmDaoSession().getEpcGoodsInfoDao().deleteAll();
        getmDaoSession().getEpcInfoDao().deleteAll();
        getmDaoSession().getUnusefulEpcDao().deleteAll();
        getmDaoSession().getTagInfoDao().deleteAll();
        getmDaoSession().getGoodsInfoDao().deleteAll();
        getmDaoSession().getRecordInfoDao().deleteAll();
    }

    public void deleteAll(boolean isContainGlobal){
        deleteAll();
        if (isContainGlobal){
            getmDaoSession().getGlobalGoodsInfoDao().deleteAll();
        }
    }

    public static SQLiteDatabase getDb() {
        if (db == null) {
            initGreenDao();
        }
        return db;
    }

    /**
     * 关闭所有的操作，数据库开启后，使用完毕要关闭
     */
    public void closeConnection() {
        closeHelper();
        closeDaoSession();
    }

    public void closeHelper() {
        if (mHelper != null) {
            mHelper.close();
            mHelper = null;
        }
    }

    public void closeDaoSession() {
        if (mDaoSession != null) {
            mDaoSession.clear();
            mDaoSession = null;
        }
    }

}
